package com.htjx.mall.controllers;

import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.htjx.mall.commons.api.Result;
import com.htjx.mall.commons.models.AlipayTrade;
import com.htjx.mall.commons.models.Order;
import com.htjx.mall.commons.models.OrderGroup;
import com.htjx.mall.commons.models.enums.SeqType;
import com.htjx.mall.commons.models.enums.TradeStatus;
import com.htjx.mall.commons.models.user.Account;
import com.htjx.mall.controllers.alipay.api.Alipay;
import com.htjx.mall.controllers.commonapi.CommonCookie;
import com.htjx.mall.services.AlipayTradeService;
import com.htjx.mall.services.OrderService;
import com.htjx.mall.services.SequenceManager;
import com.htjx.mall.services.wallet.AccountService;

@Controller
@RequestMapping("/alipay")
public class AlipayController {
	@Autowired
	private OrderService orderService;
	@Autowired
	private AccountService accountService;
	@Autowired
	private AlipayTradeService alipayTradeService;
	@Autowired
	private SequenceManager sequenceManager;
	/**
	 * 用户支付
	 * @throws Exception 
	 * **/
	@RequestMapping(value = "/submit", method = RequestMethod.POST, produces = "application/json")
	@ResponseBody
	public Result pay(@RequestParam("order_group_id") long orderGroupId, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		OrderGroup orderGroup = orderService.selectOrderGroupById(orderGroupId);
		List<Order> orderList = orderService.selectOrderByGroupId(orderGroupId);
		Account account = accountService.selectOne(orderGroup.getUser_id());
		
		orderGroup.setOrderList(orderList);
		orderGroup.setAccount(account);
		orderGroup.calc();
		
		if(orderList.size() < 1) {
			return new Result(9,"订单为空");
		}
		
		if(StringUtils.isBlank(orderList.get(0).getRec_name())) {
			return new Result(9,"收件人不能为空");
		}
		
		if(StringUtils.isBlank(orderList.get(0).getPhone())) {
			return new Result(9,"收件人手机不能为空");
		}
		
		if(StringUtils.isBlank(orderList.get(0).getAddress())) {
			return new Result(9,"收件人地址不能为空");
		}
		
		// alipay 接口
		String alipayForm = Alipay.pay(String.valueOf(orderGroup.getId()), orderGroup.getSubject(), String.valueOf(orderGroup.getPay_amount()));
		
		// 支付后，更新数据库中的订单状态，和账户信息（order order_group account）
		// order_group 
		orderGroup.setUpdate_time(new Date());
		orderGroup.setTrade_status(TradeStatus.wait_paying);
		orderService.updateOrderGroup(orderGroup, null);
		
		Map<String, Object> retBody = new HashMap<String, Object>();
		retBody.put("alipayForm", alipayForm);
		Result result = new Result(0, "支付成功");
		result.setBody(retBody);
		return result;
	}
	
	@RequestMapping(value = "/parse/callback")
	public String parseCallback(HttpServletRequest request, HttpServletResponse response) throws Exception {
		//long userId = AuthorizeList.getCurrentAuthUser(request);
		
		Map<String,String> params = new HashMap<String,String>();
		if(! Alipay.parseCallback(request, params)){
			//return new Result(9,"支付验证异常，请前往支付宝确认支付结果，如有疑问请联系客服");
			return "redirect:/mobile/commons/abnormal.html";
		} 
		
//		if(params.get("result").equals("success")) {
//			long orderGroupId = Long.parseLong(params.get("out_trade_no"));
//			OrderGroup orderGroup = orderService.selectOrderGroupById(orderGroupId);
//			List<Order> orderList = orderService.selectOrderByGroupId(orderGroupId);
//			Account account = accountService.selectOne(userId);
//			
//			orderGroup.setOrderList(orderList);
//			orderGroup.setAccount(account);
//			
//			orderGroup.setTrade_status(TradeStatus.finish);
//			orderGroup.setAccountFrozen();
//			orderGroup.setOrderListStatus();
//			
//			orderService.updateOrderGroup(orderGroup);
//		}
		
//		AlipayTrade alipayTrade = new AlipayTrade();
//		alipayTrade.setBuyer_email("test");
//		alipayTrade.setOrder_group_id(Long.parseLong(params.get("out_trade_no")));	
//		alipayTrade.setOut_trade_no(params.get("out_trade_no"));
//		alipayTrade.setPayment_type("2");
//		alipayTrade.setTotal_fee("total_fee");
//		alipayTrade.setTrade_no(params.get("trade_no"));
//		alipayTrade.setTrade_status("trade_status");
//		
//		alipayTradeService.insertOne(alipayTrade);
		
		CommonCookie.setAlipayCallback(params, response);
//		System.out.println("callback:"+params.toString());
//		Result result = new Result(0, "支付成功");
//		result.setBody(params);
		return "redirect:/mobile/call_back_url.html";
	}
	
	@RequestMapping(value = "/callback", method = RequestMethod.GET, produces = "application/json")
	@ResponseBody
	public Result getCallback(HttpServletRequest request) {
		Map<String,String> params = CommonCookie.getAlipayCallback(request);
		Result result = new Result(0, "查询成功");
		result.setBody(params);
		return result;
	}
	
	@RequestMapping(value = "/parse/notify")
	public void parseNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PrintWriter out = response.getWriter();
		Map<String,String> params = new HashMap<String,String>();
		Map<String,String> notify_params = new HashMap<String,String>();
		if(! Alipay.parseNotify(request, params, notify_params)){
			out.println("fail");	//请不要修改或删除
			return;
		} 
		
		long orderGroupId = Long.parseLong(notify_params.get("out_trade_no"));
		OrderGroup orderGroup = orderService.selectOrderGroupById(orderGroupId);
		if(orderGroup == null) {
			out.println("fail");	//请不要修改或删除
			return;
		}
		
		List<Order> orderList = orderService.selectOrderByGroupId(orderGroupId);
		Account account = accountService.selectOne(orderGroup.getUser_id());
		orderGroup.setOrderList(orderList);
		orderGroup.setAccount(account);
		orderGroup.setAccountFrozen();
		orderGroup.setOrderListStatus();
		orderGroup.setUpdate_time(new Date());
		
		AlipayTrade alipayTrade = new AlipayTrade();
		alipayTrade.setPayment_type(notify_params.get("payment_type"));
		alipayTrade.setTrade_no(notify_params.get("trade_no"));
		alipayTrade.setBuyer_email(notify_params.get("buyer_email"));
		alipayTrade.setOut_trade_no(notify_params.get("out_trade_no"));
		alipayTrade.setTrade_status(notify_params.get("trade_status"));
		alipayTrade.setTotal_fee(notify_params.get("total_fee"));
		
		if(notify_params.get("trade_status").equals("TRADE_SUCCESS") || notify_params.get("trade_status").equals("TRADE_FINISHED")) {
			orderGroup.setTrade_status(TradeStatus.finish);
		} else {
			orderGroup.setTrade_status(TradeStatus.break_off);
		}
		
		orderService.updateOrderGroup(orderGroup, alipayTrade);
		
		if(notify_params.get("trade_status").equals("TRADE_SUCCESS") || notify_params.get("trade_status").equals("TRADE_FINISHED")) {
			out.println("success");
		} else {
			out.println("fail");
		}
	}
	
	@RequestMapping(value = "/notify", method = RequestMethod.GET, produces = "application/json")
	@ResponseBody
	public Result getNotify(HttpServletRequest request) {
		Map<String,String> params = CommonCookie.getAlipayNotify(request);
		Result result = new Result(0, "查询成功");
		result.setBody(params);
		return result;
	}
	
	@RequestMapping(value = "/test")
	public void test(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PrintWriter out = response.getWriter();
		out.println("success");
	}
}
